export default{
  namespaced: true,
  state:{
    name:'cart模块',
    carts:[]
},
  mutations:{
    SET_CART(state,payload){
      let target=state.carts.find(item=>item.id===payload.id)
      if(!target){
        let obj={
          id:payload.id,
          title:payload.title,
          price:payload.price,
          count:1
        }
        state.carts.push(obj)
      }else{
        target.count++
      }
    },
    DECREASE_CART(state,payload){
      let target=state.carts.find(item=>item.id===payload.id)
      target.count--
      state.carts=state.carts.filter(item=>item.count!==0)
    }
  },
  actions:{
    ADD_TO_CART({commit},payload){
      commit('SET_CART',payload)
      commit('product1/DECREASE_INVENTORY', payload, { root: true })
    },
    REMOVE_CART({commit},payload){
      commit('DECREASE_CART',payload)
      commit('product1/INVENTORY', payload, {root: true})
    }
  },
  getters:{
    total(state){
      return (state.carts.reduce((total,item)=>{
        return total +=item.price+item.count
      },0)).toFixed(2)
    }
  },
}